package Servlet;

import DAO.CustomerDAO;
import javabean.Customer;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/Recharge")
public class RechargeServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 设置响应内容类型为文本类型
        response.setContentType("text/html;charset=UTF-8");

        // 获取充值金额
        String amount = request.getParameter("rechargeAmount");

        // 从session中获取当前登录用户的信息，这里假设登录后将用户信息保存在session中
        Customer customer = (Customer) request.getSession().getAttribute("loginCustomer");

        // 执行充值逻辑，更新账户余额
        CustomerDAO customerDAO = new CustomerDAO();
        boolean success = false;
        try {
            // 获取当前账户余额
            double currentBalance = customer.getCustomerBalance();
            // 计算充值后的余额
            double newBalance = currentBalance + Double.parseDouble(amount);
            // 更新余额
            customer.setCustomerBalance(newBalance);
            // 更新账户余额
            success = customerDAO.RevisionCustomer(customer);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        // 返回充值结果给客户端
        PrintWriter out = response.getWriter();
        if (success) {
            out.println("<script>alert('充值成功');window.location.href='Balance.jsp'</script>");
        } else {
            out.println("充值失败");
        }
        out.close();
    }
}
